﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using OA.Service.Model.Data;

namespace OA.SSO.Lib
{
    public class LoginPage : System.Web.UI.Page
    {
        /// <summary>
        /// 登陆用户
        /// </summary>
        public static User LoginUser { get { return HttpContext.Current.Session["LoginUser"] as User; } set { HttpContext.Current.Session["LoginUser"] = value; } }

        static string ServerUrl = System.Configuration.ConfigurationManager.AppSettings["SSOServerUrl"];

        public LoginPage()
        {
            this.Load += new EventHandler(LoginPage_Load);
        }

        void LoginPage_Load(object sender, EventArgs e)
        {
            ValidateLogin();
        }

        /// <summary>
        /// 登陆验证
        /// </summary>
        public static void ValidateLogin()
        {
            if (LoginUser == null)
            {
                var Request = HttpContext.Current.Request;
                var Response = HttpContext.Current.Response;
                var Server = HttpContext.Current.Server;
                var Token = Request.QueryString["Token"];
                if (string.IsNullOrEmpty(Token))
                {
                    RedirectToLogin();
                }
                else
                {
                    try
                    {
                        var getUserUrl = ServerUrl + "/Tools/GetLoginUserByToken?Token=" + Server.UrlEncode(Token);
                        var client = new System.Net.WebClient();
                        client.Encoding = System.Text.Encoding.UTF8;
                        var userXml = client.DownloadString(getUserUrl);
                        LoginUser = Common.SerializationHelper.DeSerialize<User>(userXml);
                    }
                    catch (Exception e)
                    {
                        RedirectToLogin();
                    }
                }
            }
        }

        private static void RedirectToLogin()
        {
            var Request = HttpContext.Current.Request;
            var Response = HttpContext.Current.Response;
            var Server = HttpContext.Current.Server;
            var tokenUrl = ServerUrl + "/Tools/GetToken";
            tokenUrl += "?BackUrl=" + Server.UrlEncode(Request.Url.AbsoluteUri);
            if ("XMLHttpRequest".Equals(Request.Headers["X-Requested-With"]) == false) //普通请求
            {
                Response.Redirect(tokenUrl, true);
            }
            else  //ajax请求
            {
                Response.Write("{success:false,message:'尚未登陆',LoginUrl:'" + tokenUrl + "'}");
                Response.End();
            }
        }
    }
}